<template>
    <div class='content'>
        <div class="profile_page">
                <head-top  :go-back='goBack'  :head-title="profiletitle"></head-top>
        </div>
        <div class="formContain">
            <titlebar :title-left='titleLeft'></titlebar>
            <ul>
                <li class="flex">
                    <span class="label"><i class="require">*</i>开始时间</span>
                    <div @click="showdatepicker($event,'startTime')">
                        <input type="text"  id="begin" placeholder="请选择时间" :value="datas.startTime"  readonly>
                        <img src="@/assets/images/img/calendarIcon.png" alt="" srcset="" >
                    </div>
                </li>
                 <li class="flex">
                    <span class="label"><i class="require">*</i>结束时间</span>
                    <div @click="showdatepicker($event,'endTime')">
                        <input type="text"  id="end" placeholder="请选择时间" :value="datas.endTime"  readonly>
                        <img src="@/assets/images/img/calendarIcon.png" alt="" srcset="" >
                    </div>
                </li>
                 <li class="flex">
                    <span class="label"><i class="require">*</i>调休时长（小时）</span>
                    <div>
                      <div class="van-cell van-field number-input">
                        <div class="van-cell__value van-cell__value--alone">
                          <div class="van-field__body">
                            <MyNumberInput :point="1" :max="999999" placeholder="请输入调休时长" v-model.number="datas.offAmount"></MyNumberInput>
                          </div>
                        </div>
                      </div>
                        <!--<van-field v-model="datas.offAmount" maxlength="6" placeholder="请输入调休时长" @input="checkNum" type="number" step="0.1" input-align="right"/>-->
                    </div>
                </li>
                 <li class="flex">
                    <span class="label"><i class="require">*</i>调休类型</span>
                    <div @click="showpicker($event,'offTypeName','调休类型')">
                        <input type="text"  id="typeName" placeholder="请选择调休类型" :value="datas.offTypeName"  readonly>
                        <span class="iconfont icon-xiala"></span>
                    </div>
                </li>
                  <li class="flex">
                    <span class="label">剩余调休时长（小时）</span>
                    <div>
                      <div class="van-cell van-field number-input">
                        <div class="van-cell__value van-cell__value--alone">
                          <div class="van-field__body">
                            <MyNumberInput :point="1" :max="999999" placeholder="系统自动带出" v-model.number="datas.offAmountRemain" disabled></MyNumberInput>
                          </div>
                        </div>
                      </div>
                        <!--<van-field v-model="datas.offAmountRemain" maxlength="6" placeholder="系统自动带出" type="number" step="0.1" input-align="right" disabled/>-->
                    </div>
                </li>
            </ul>

        </div>
         <div class="formContain">
            <titlebar :title-left='titleLeft1'></titlebar>
            <ul>
                <li class="flex">
                    <div class='full_width' style="min-height:2rem">
                      <i class="require">*</i>
                        <van-field class='full_width'  rows="1" autosize v-model="datas.remark" placeholder="请输入调休原因" type="textarea" input-align="left"/>
                    </div>
                </li>
                <li class="flex">
                    <span class="label">上传附件</span>
                    <div>
                      <input type="text" v-model="fileName" disabled style="background: transparent;width: 10rem;position: absolute;padding-right: 1rem">
                      <van-uploader :after-read="afterRead" :before-read="beforeRead" id="file">
                        <span class="iconfont icon-hao"></span>
                      </van-uploader>
                    </div>
                </li>
            </ul>
         </div>
         <div class="align_center foot-button" >
              <van-button class="cancel-btn" type="primary" @click="$router.go(-1)">取消</van-button>
            <van-button class="primary-btn" type="primary" @click="saveBreak">提交</van-button>
         </div>
        <van-picker id="picker"   show-toolbar  :title="title" v-show='pickershow' :columns="columns" @cancel="onCancel" @confirm="onConfirm" />
      <van-popup v-model="pickershow" position="bottom">
        <van-picker id="picker" value-key="name"  show-toolbar  :title="title" :columns="columns" @cancel="onCancel" @confirm="onConfirm"/>
      </van-popup>
    </div>
</template>

<script>
    import headTop from '@/components/header/head'
     import titlebar from '@/components/titlebar3/titlebar3';
    import {canSave,startProcess,uploadFile,processInstance,breakOffType,breakOffRemain,saveBreakOff} from '@/service/getData';
    import {getStore,getDefault} from '@/assets/config/mUtils';
    import { Dialog,Toast} from 'vant';
    import MyNumberInput from '@/components/numberInput/numberInput';
    export default {
    	data(){
            return{
                profiletitle:'调休',
                goBack:true,
                titleLeft:'调休信息',
                titleLeft1:'调休原因',
                show:false, //控制日期显示隐藏
                pickershow:false,//控制下拉选显示隐藏
                pickerName:'',//当前控制日期的控件
                currentTime:new Date(),
                fileName:'',
                screenHeight:'',
                startManagerId:'',
                bussinessTable:'ACT_ATND_BREAK_OFF',
                datas:{
                  endTime:'',
                  startTime:'',
                  offTypeName:'',
                  offAmount:'',
                  offAmountRemain:0,
                  remark:'',
                  attachmentId:''
                },
                title:'标题',//下拉框标题
                columns: []  //下拉框数据
            }
        },
        created(){
          var processData = {};
          processData.processDefinitionKey = 'breakOffTheOff';
          processData.app_userId = getStore('user_id');
          processData.CHECK_TIME = new Date().getTime().toString();
          processData.CHECK_SIGN = this.$md5(processData.app_userId + processData.CHECK_TIME +"3a28fba00c015e0df7f88556c91cb7fc");
          // processData = JSON.stringify(processData);
          startProcess(processData).then(res=>{
//            console.log(res);
            this.startManagerId = res.data.startManagerId;
          });
          var data = getDefault();
          /*调休类型*/
          breakOffType(data).then(res=>{
            this.columns = res.data["3225"];
          });
        },
        mounted(){
          this.screenHeight = document.documentElement.clientHeight;
        },
        updated () {
          let that = this;
          this.$nextTick(function () {
            let $inputs = Array.from(document.getElementsByTagName('input'));
            /*let body = document.body;
            $inputs.forEach(item => { // 定时器是处理多个input间快速切换闪屏问题，可省略
                item.onblur = function () { // onblur是核心方法
                    clearTimeout(body.timer);
                    body.timer = setTimeout(() => {
                    window.scroll(0, 0);
                    window.innerHeight = window.outerHeight = that.screenHeight
                    }, 150)
                }
                item.onfocus = function () {
                    clearTimeout(body.timer)
                }
            })*/
            let body = document.body;
            $inputs.forEach(item => {
              item.onblur = function () { // onblur是核心方法
                window.scroll(0, 0);
                window.innerHeight = window.outerHeight = that.screenHeight;
                //console.log(that.screenHeight);
              }
            })
          })
        },
        components:{
            headTop,
            titlebar,
          MyNumberInput
        },
        methods:{
          // checkNum(){
          //   this.datas.offAmount = parseFloat(this.datas.offAmount)
          // },
          addZero(num){
            var addNum = num<10?"0"+num:num;
            return addNum;
          },
            datetimeSelect(value){
                this.show = false;
                var date =  value;
                var val = date.getFullYear() + '-'+this.addZero(date.getMonth()+1) + '-'+ this.addZero(date.getDate())+' '+this.addZero(date.getHours()) + ':'+ this.addZero(date.getMinutes())+':'+"00";
                this.$set(this.datas,this.pickerName,val);
                // document.getElementById(this.pickerName).value = val;
              if(this.datas.startTime!=''){
                var breakData = {};
                breakData.personId = getStore('user_id');
                breakData.startTime = this.datas.startTime;
                breakData.app_userId = getStore('user_id');
                breakData.CHECK_TIME = new Date().getTime().toString();
                breakData.CHECK_SIGN = this.$md5(breakData.app_userId + breakData.CHECK_TIME +"3a28fba00c015e0df7f88556c91cb7fc");
                breakOffRemain(breakData).then(res=>{
                  this.datas.offAmountRemain = res.data.data;
                })
              };
              if(this.datas.endTime != ""){
                if(this.datas.startTime >= this.datas.endTime){
                  Dialog.alert({
                    title: '',
                    message: '开始时间不能大于结束时间'
                  });
                  this.datas.endTime = '';
                }
              };
            },
            onConfirm(value){
                this.$set(this.datas,this.pickerName,value.text);
                 this.pickershow = false;
            },
            cancel() {
                this.show = false;
            },
            onCancel(){
                this.pickershow = false;
            },
            showdatepicker(event,name){
                this.show = true;
                this.pickerName = name;
            },
            showpicker(event,name,title){
                this.pickershow = true;
                this.pickerName = name;
                this.title = title;
            },
          beforeRead(file) {
            var imgType = file.type.toLocaleLowerCase();
            if (imgType != 'image/jpg'&&imgType != 'image/jpeg'&&imgType != 'image/png'&&imgType != 'image/gif'&&imgType != 'image/bmp') {
              Toast('请上传图片');
              return false;
            }

            return true;
          },
            afterRead(file) {
              // 此时可以自行将文件上传至服务器
              //console.log(file.file.name);
              Toast.loading({
                duration: 0,   // 持续展示 toast
                mask: true,
                message: '正在上传...'
              });
              var formData = new FormData();
              formData.append("uploadFile", file.file);
              uploadFile(formData).then(res=>{
                this.fileName = file.file.name;
                this.datas.attachmentId = res.fileId;
                Toast.clear();
              })
            },
            findId(data,curName){
              for(var i=0;i<data.length;i++){
                if(data[i].text == curName){
                  return data[i].id;
                }
              }
            },
            saveBreak(){
              Toast.loading({
                duration: 0,   // 持续展示 toast
                mask: true,
                message: '正在提交...'
              });
              if(this.datas.offAmountRemain < this.datas.offAmount){
                Toast.clear();
                Dialog.alert({
                  title: '提示',
                  message: '剩余调休时长不足'
                })
              }else if(this.datas.offAmount == 0){
                Toast.clear();
                Dialog.alert({
                  title: '提示',
                  message: '调休时长不能为0'
                })
              }else {
                var savaBreakDatas = this.datas;
                savaBreakDatas.applyUser = getStore('user_id');
                savaBreakDatas.app_userId = getStore('user_id');
                savaBreakDatas.CHECK_TIME = new Date().getTime().toString();
                savaBreakDatas.CHECK_SIGN = this.$md5(savaBreakDatas.app_userId + savaBreakDatas.CHECK_TIME +"3a28fba00c015e0df7f88556c91cb7fc");
                savaBreakDatas.offType = this.findId(this.columns,this.datas.offTypeName);

                var data = {};
                data.app_userId = getStore('user_id');
                data.processRespondentUserId = getStore('user_id');
                data.day = (this.datas.offAmount)/8;
                data.processType = "KQ";
                data.CHECK_TIME = new Date().getTime();
                data.CHECK_SIGN = this.$md5(data.app_userId + data.CHECK_TIME +"3a28fba00c015e0df7f88556c91cb7fc");
                data.startManagerId = this.startManagerId;
                data.bussinessTable = this.bussinessTable;
                data.processDefinitionKey = 'breakOffTheOff';

                // 判断是否可以提交
                canSave(data).then(res=>{
                  if(res.code == 200){
                    if(!res.data.flag){
                      Toast.clear();
                      Dialog.confirm({
                        title: '提示',
                        message: res.data.message
                      }).then(() => {
                        saveBreakOff(savaBreakDatas).then(res=>{
//                console.log(res);
                          if(res.code == 200){
                            data.bussinessIds = res.data;
                            processInstance(data).then(res1=>{
                              if(res1.code == 200){
                                Toast.clear();
                                Dialog.alert({
                                  title: '提示',
                                  message: '提交审批成功'
                                }).then(() => {
                                  this.$router.go(-1);
                                });
                              }
                            })
                          }else if(res.code == 400){
                            Toast.clear();
                            Dialog.alert({
                              title: '提示',
                              message: res.msg
                            })
                          }
                        })
                      }).catch(() => {
                        return false;
                      });
                    }else{
                      saveBreakOff(savaBreakDatas).then(res=>{
//                console.log(res);
                        if(res.code == 200){
                          data.bussinessIds = res.data;
                          processInstance(data).then(res1=>{
                            if(res1.code == 200){
                              Toast.clear();
                              Dialog.alert({
                                title: '提示',
                                message: '提交审批成功'
                              }).then(() => {
                                this.$router.go(-1);
                              });
                            }
                          })
                        }else if(res.code == 400){
                          Toast.clear();
                          Dialog.alert({
                            title: '提示',
                            message: res.msg
                          })
                        }
                      })
                    }
                  }else if(res.code==400){
                    Toast.clear();
                    Dialog.alert({
                      title: '提示',
                      message: res.msg
                    })
                  }
                })


              }

            }
        }
    }

</script>

<style lang="scss" scoped>
    @import '../../assets/style/mixin';
    @import '../../assets/style/public';
    .formContain{
        background: #fff;
        ul{
            padding: 0 .54rem;
            .flex{
                justify-content: space-between;
                align-items: center;
                line-height: 2rem;
                border-bottom: 1px solid #e0e0e0;
                padding: 0 .3rem;
                &:nth-last-of-type(1){
                    border: none;
                }
                .label{
                    font-size: .56rem;
                    line-height: 2rem;
                    color: #333333;
                }
                div{
                    display: flex;
                    justify-content: flex-end;
                    align-items: center;
                    position: relative;
                  flex-grow: 1;
                    img{
                        width: .68rem;
                        height: .64rem;
                    }
                    input{
                        color: #323233;
                        text-align: right;
                        font-size: .48rem;
                        padding-right: .48rem;
                        border: none;
                        &:-ms-input-placeholder{
                             color: #aaa;
                             font-size: .48rem;

                        }
                    }
                    .file{
                        width: 2rem;
                        height: 1rem;
                        font-size: 10rem;
                        opacity: 0;
                        position: absolute;
                        right: 0;
                    }
                    .van-cell{
                        font-size: .48rem;
                        padding-right: .48rem;
                        padding: 0;
                        color: #aaa;
                        .van-field__control{
                            color: #aaa;
                        }
                    }

                }
            }
        }
    }
    .foot-button{
        margin-top: 2rem;
        margin-bottom: .4rem;
        .cancel-btn{
            margin-right: 1rem;
        }
    }
    #datetime-picker,#picker{
        position: fixed;
        width: 100%;
        bottom: 0;
    }
    .require{
      color: red;
      margin-right: 4px;
      font-style: inherit;
      font-size: 14px;
    }
</style>
